﻿//======================================================================
//
//        Copyright (C) 2015   
//        All rights reserved
//
//        filename : ChangeBadCard
//        description : 退换坏卡回收
//        created by XXX at  20150821
//
//======================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CardLogistics.Web.Components;
using System.Data;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;

namespace CardLogistics.Web.MainPage.CardRecovery.ChangeBadCard
{
    public partial class ListInfo : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // WebUserControl_ToolBar1.DeleteEvent += new EventHandler(WebUserControl_ToolBar1_DeleteEvent);
            if (!IsPostBack)
            {
                txt_StartDate.Text = DateTime.Now.ToString("yyyyMMdd");
                txt_EndDate.Text = DateTime.Now.ToString("yyyyMMdd");
                //BindRpt("bgTime=" + txt_StartDate.Text + "&endTime=" + txt_StartDate.Text + "");
            }
        }



        protected void btn_Search_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txt_StartDate.Text.Trim()) || string.IsNullOrEmpty(txt_StartDate.Text.Trim()))
            {
                ShowMessageBox("请输入完整的查询时间段！");
                return;
            }
            BindRpt("bgTime=" + txt_StartDate.Text + "&endTime=" + txt_EndDate.Text + "");
        }
        /// <summary>
        /// 绑定Rpt数据
        /// </summary>
        private void BindRpt(string strWhere)
        {
            try
            {
                string a1 = HttpGet("http://10.0.8.149:8083/api/logistics/GetCardInfo?" + strWhere);

                DataTable dt0 = JsonToDataTable(a1.Replace(@"\", ""));


                rptList.DataSource = dt0;
                rptList.DataBind();
            }
            catch (Exception ex)
            {
                ShowMessageBox(ex.ToString());
            }
            //int recordCount = 0;
            //int pageCount = 0;
            //DataTable dt = CardLogistics.DAL.CommonData.QuickPage_Oracle("v_jy_tlmngtxndtltb", "", " rlsdate ", WebPageSize, WebPageIndex, "", "*", out pageCount, out recordCount);
            //SetNetPagerHtml(AspNetPager1, dt, rptList, recordCount);
            #region 导出数据


            //导出语句
            //string strExpSql = "select RLSDATE 结算日期,RltxncodeType 外部交易类型,RltxncodeTypeName 业务类型,RLCARDFACENO 卡面号,RlcdphykindName 卡物理类型,RLDPTAMT 实退卡押金,RLAFTBAL 退换卡卡金额,RLRDATE 交易发生日期,RladjflagName 调整结果标志位,RLADJSETTDATE 调整结算日期 from v_jy_tlmngtxndtltb order by rlsdate";
            //if (!Page.IsClientScriptBlockRegistered("regExportSql"))
            //    Page.RegisterClientScriptBlock("regExportSql", "<script language=\"Javascript\">var qsql=\"" + Server.UrlEncode(strExpSql) + "\";</script>");
            #endregion
        }




        public static string HttpGet(string url)
        {
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.Accept = "textml, application/xhtml+xml, */*";
            request.ContentType = "application/json";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }


        #region 将json转换为DataTable
        /// <summary>
        /// 将json转换为DataTable
        /// </summary>
        /// <param name="strJson">得到的json</param>
        /// <returns></returns>
        private DataTable JsonToDataTable(string strJson)
        {
            //转换json格式
            strJson = strJson.Replace(",\"", "*\"").Replace("\":", "\"#").ToString();
            //取出表名   
            var rg = new Regex(@"(?<={)[^:]+(?=:\[)", RegexOptions.IgnoreCase);
            string strName = rg.Match(strJson).Value;
            DataTable tb = null;
            //去除表名   
            strJson = strJson.Substring(strJson.IndexOf("[") + 1);
            strJson = strJson.Substring(0, strJson.IndexOf("]"));
            //获取数据   
            rg = new Regex(@"(?<={)[^}]+(?=})");
            MatchCollection mc = rg.Matches(strJson);
            for (int i = 0; i < mc.Count; i++)
            {
                string strRow = mc[i].Value;
                string[] strRows = strRow.Split('*');
                //创建表   
                if (tb == null)
                {
                    tb = new DataTable();
                    tb.TableName = strName;
                    foreach (string str in strRows)
                    {
                        var dc = new DataColumn();
                        string[] strCell = str.Split('#');
                        if (strCell[0].Substring(0, 1) == "\"")
                        {
                            int a = strCell[0].Length;
                            dc.ColumnName = strCell[0].Substring(1, a - 2);
                        }
                        else
                        {
                            dc.ColumnName = strCell[0];
                        }
                        tb.Columns.Add(dc);
                    }
                    tb.AcceptChanges();
                }
                //增加内容   
                DataRow dr = tb.NewRow();
                for (int r = 0; r < strRows.Length; r++)
                {
                    dr[r] = strRows[r].Split('#')[1].Trim().Replace("，", ",").Replace("：", ":").Replace("\"", "");
                }
                tb.Rows.Add(dr);
                tb.AcceptChanges();
            }
            return tb;
        }
        #endregion

    }
}